#include "index.h"

static void
index_list_dispose(void *list, void *extra)
{
	(void) extra;

	list_dispose(list);
	free(list);
}

Disposer index_list_disposer = {
	.extra = NULL,
	.dispose = index_list_dispose
};

Nit_error
index_init(Index *index, int bin_pos)
{
	return map_init(index, &index_list_disposer, bin_pos);
}

Nit_error
index_add(Index *index, Set *keys, void *dat)
{
	int bin;
	Set_entry *entry;
        Nit_error error;

	set_foreach (keys, bin, entry) {
	        List *list;

		if (map_get(index, entry->key_len,
			    entry->dat, (void **) &list)) {
			List_entry *lentry;

		        list_foreach (lentry, list)
				if (lentry->data == dat)
				        break;

			if (lentry)
				continue;
		} else {
			if (!(list = malloc(sizeof(*list))))
				return NIT_ERROR_MEMORY;

			list_init(list, NULL);

			if ((error = map_add(index, entry->key_len,
					     entry->dat, list))) {
				free(list);
				return error;
			}
		}

		if ((error = list_add(list, NULL, dat)))
			return error;
	}

	return NIT_ERROR_FINE;
}

int
index_get(const Index *index, uint32_t key_len, const void *key, List **val)
{
	return map_get(index, key_len, key, (void **) val);
}
